import React, { PureComponent, Fragment } from 'react';
import moment from 'moment';
import { connect } from 'dva';
import {
  Button,
  Tag,
  Modal,
  Form,
  message,
  Tooltip,
  Radio,
  Input,
  Icon,
  Drawer,
  Row,
  Col,
  Switch,
  Progress, Select, Calendar, Typography, Badge, Table,
} from 'antd';

import find from 'lodash/find';
import OrganizationChart from '@dabeng/react-orgchart';
import debounce from 'lodash/debounce';
import { ellipsis, afterCloseModal, deleteTreeChildren } from '@/utils/utils';
import BuildModalTitle from '@/components/BuildModalTitle';
import AddOrEditPrice from './AddOrEditPrice';
import department from './../../images/department.png';

const RadioButton = Radio.Button;
const { Text } = Typography;
const RadioGroup = Radio.Group;
const { confirm } = Modal;
const FormItem = Form.Item;

@connect(({ departments, loading, global }) => ({
  departments,
  global,
  loading: loading.models.departments,
}))
@Form.create()
class BasicList extends PureComponent {
  constructor(props) {
    super(props);
    this.permissions = JSON.parse(sessionStorage.getItem('permissions'));
    this.state = {
      showAddBtn: find(this.permissions, { name: 'structure_operation' }),
      visible: false,
      done: false,
      page: 1,
      per_page: 30,
      username: '',
      editRecord: {},
      selectedRowKeys: [],
      btnLoading: false,
      nowDate: moment().format('YYYY-MM-DD'),
    };
  }


  componentDidMount() {

    const { dispatch } = this.props;
    const {
      departments: { pageLoaded, scrollData },
    } = this.props;
    console.log('pageLoaded', pageLoaded);
    const table = document.querySelector('.react-grid-Canvas');
    if (pageLoaded) {
      // setTimeout(() => {
      //   table.scrollTop = scrollData.y;
      //   table.scrollLeft = scrollData.x;
      // }, 0);

    } else {
      const {
        departments: { searchParams },
      } = this.props;
      console.log('searchParams', searchParams);
      dispatch({
        type: 'departments/fetch',
        payload: searchParams,
        callback: () => {
          const { dispatch } = this.props;
          dispatch({
            type: 'departments/changeLoaded',
          });
        },
      });

    }
    window.addEventListener('resize', this.resize);
    // table.addEventListener('scroll', debounce(this.scroll, 150));
  }


  componentWillUnmount() {
    console.log('componentWillUnmount');
    window.removeEventListener('resize', this.resize);
    return;
    const table = document.querySelector('.ant-table-body');
    table.removeEventListener('scroll', debounce(this.scroll, 300));
  }

  handleSearch = (values, cb) => {
    console.log('handleSearch', values);
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: 'departments/fetch',
      payload: {
        ...values,
      },
      callback() {
        console.log('handleSearch callback');
        if (cb) cb();
      },
    });
  };
  handleEdit = () => {
    const formValues = this.EditForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    console.log('formValues', formValues);
    const that = this;
    this.props.dispatch({
      type: 'departments/edit',
      payload: {
        ...formValues,
        parent_id:formValues.parent_id?formValues.parent_id.split('$')[0]:'',
        id: this.state.editRecord.id,
      },
      callback() {
        message.success('修改部门成功');
        that.setState({
          editModal: false,
        });
        const {
          departments: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };
  selectNode = (nodeData) => {
    console.log('nodeData', nodeData);
    alert('Hi All. I\'m ' + nodeData.name + '. I\'m a ' + nodeData.title + '.');
  };
  handleAdd = () => {
    const formValues = this.AddForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    const that = this;
    this.props.dispatch({
      type: 'departments/add',
      payload: {
        ...formValues,
        parent_id:formValues.parent_id?formValues.parent_id.split('$')[0]:'',
      },
      callback() {
        message.success('添加部门成功');
        that.setState({
          addModal: false,
        });
        const {
          departments: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };
  handleDelete = id => {
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: 'departments/remove',
      payload: { id },
      callback: () => {
        message.success('删除部门成功');
        const {
          departments: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };

  renderSimpleForm() {
    return (
      <Form layout="inline" className="search-form" style={{ padding: '5px 10px 0' }}>
        <FormItem>
          {
            find(this.permissions, { name: 'department_operation' }) &&
            <Button
              icon="plus"
              style={{ marginLeft: 8 }}
              type="primary"
              onClick={
                () => {
                  this.setState({
                    addModal: true,
                  });
                }
              }
            >
              添加部门
            </Button>
          }
        </FormItem>

      </Form>
    );
  }

  render() {
    const that = this;
    const {
      departments: { data, loading, tableY, meta, searchParams, selectedRowKeys, additional },
      global: { gridTableW },
    } = this.props;
    console.log('data', deleteTreeChildren(data));
    const columns = [
      { title: '部门名称', dataIndex: 'name', key: 'name',
        render: (val, record) =>{
            return <span style={{fontWeight:'bold'}}><img src={department} style={{width:'20px',height:'20px',marginRight:'10px'
            ,position:'relative',top:'-4px'}} alt=""/>{val}</span>
        }
        },
      { title: '备注', dataIndex: 'remark', key: 'remark', width: '40%' },
      {
        title: '操作',
        key: 'right',
        width: 200,
        classname: 'operate',
        render: (val, record) => <Fragment>
          {
            find(this.permissions, { name: 'personnel_management' }) &&
              <Fragment>
                <Button
                  type="primary"
                  size="small"
                  icon="edit"
                  onClick={(e) => {
                    e.stopPropagation();
                    this.setState({
                      editRecord: record,
                      editModal: true,
                    });
                  }
                  }
                >编辑
                </Button>
                <Button
                  type="danger"
                  size="small"
                  icon="delete"
                  onClick={(e) => {
                    e.stopPropagation();
                    confirm({
                      title: `确定要删除"${record.name}"吗?`,
                      content: '请谨慎操作！',
                      okText: '确定',
                      okType: 'danger',
                      cancelText: '取消',
                      centered: true,
                      maskClosable: true,
                      onOk() {
                        that.handleDelete(record.id);
                      },
                      onCancel() {
                        console.log('Cancel');
                      },
                    });
                  }
                  }
                >删除
                </Button>
              </Fragment>
          }

        </Fragment>,
      },
    ];

    return <div className="custom-card">
      <div className="table-title"><span className={'title-item'}>部门管理</span>
      </div>
      <div className="table-page" style={{ padding: '0' }}>
        <div className="table-condition">{this.renderSimpleForm()}</div>
        <div className={'table-data-content'} style={{ padding: '0 16px' }}>

          <Table  className="custom-small-table meter-table vendor-meter"
                  rowKey={record => record.id}
                 bordered pagination={false} columns={columns}
                 dataSource={data}/>
        </div>
      </div>
      <Modal
        title={<BuildModalTitle visible={this.state.addModal} modalClass="addModal"
                                title={`添加部门`}/>}
        destroyOnClose
        visible={this.state.addModal}
        centered
        onOk={this.handleAdd}
        className="addModal"

        afterClose={() => {
          afterCloseModal(); // destroyOnClose需要
        }}
        onCancel={() => {
          this.setState({ addModal: false, editRecord: {} });
        }}

      >
        <AddOrEditPrice
          type={'add'}
          data={data}
          wrappedComponentRef={(inst) => this.AddForm = inst}
        />

      </Modal>
      <Modal
        title={<BuildModalTitle visible={this.state.editModal} modalClass="editModal"
                                title={`修改 ${this.state.editRecord.name}`}/>}
        destroyOnClose
        visible={this.state.editModal}
        centered
        onOk={this.handleEdit}
        className="editModal"
        afterClose={() => {
          afterCloseModal(); // destroyOnClose需要
        }}
        onCancel={() => {
          this.setState({ editModal: false, editRecord: {} });
        }}

      >
        <AddOrEditPrice
          type={'edit'}
          data={data}
          editRecord={this.state.editRecord}
          wrappedComponentRef={(inst) => this.EditForm = inst}
        />

      </Modal>
    </div>;
  }
}

export default BasicList;
